<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/12/6/006
 * Time: 15:31
 */

namespace app\api\model;


use app\api\service\Token;
use app\lib\exception\AddressException;
use think\Db;
use think\Exception;

class Address extends BaseModel {

    protected $hidden = ['update_time','create_time', 'province', 'city', 'area'];

    /**
     * 省
     * @return \think\model\relation\belongsTo
     */
    public function regionProvince() {
        return $this->belongsTo('Region', 'province', 'region_id');
    }

    /**
     * 市
     * @return \think\model\relation\belongsTo
     */
    public function regionCity() {
        return $this->belongsTo('Region', 'city', 'region_id');
    }

    /**
     * 区
     * @return \think\model\relation\belongsTo
     */
    public function regionArea() {
        return $this->belongsTo('Region', 'area', 'region_id');
    }

    /**
     * 获取收货地址列表
     * @return false|static[]
     */
    public static function getAddressList() {

        $uid = Token::getCurrentUid();

//        $data = self::with(['regionProvince', 'regionCity', 'regionArea'])
//            ->where('member_id', $uid)
//            ->all();

        $data = self::with(['regionProvince', 'regionCity', 'regionArea'])->where('member_id', '=', $uid)->order('is_default desc, id desc')->select();

        return $data;
    }

    /**
     * 获取用户默认收货地址
     * @param $member_id
     * @return array|null|\PDOStatement|string|\think\Model
     */
    public static function getDefaultAddressInfo($member_id) {

        $data = self::with(['regionProvince', 'regionCity', 'regionArea'])
            ->where('is_default', 1)
            ->where('member_id', $member_id)
            ->find();

        return $data;
    }

    /**
     * 根据ID获取用户收货地址
     * @param $id
     * @param $member_id
     * @return array|null|\PDOStatement|string|\think\Model
     */
    public static function getAddressInfoById($id, $member_id) {
        $data = self::with(['regionProvince', 'regionCity', 'regionArea'])
            ->where('id', '=', $id)
            ->where('member_id', '=', $member_id)
            ->find();

        return $data;
    }

    /**
     * 创建或者更新收货地址
     * @param $param
     * @return bool
     * @throws Exception
     */
    public static function createOrUpdateAddress($param) {

        $id = isset($param['id']) ? $param['id'] : 0;
        $member_id = Token::getCurrentUid();

        $data = [
            'linkman' => $param['linkman'],
            'mobile' => $param['mobile'],
            'address' => $param['address'],
            'province' => $param['province'],
            'city' => $param['city'],
            'area' => $param['area'],
        ];

        Db::startTrans();
        try {
            if ($param['is_default'] == 1) {
                self::update(['is_default' => 0], ['member_id' => $member_id]);
                $data['is_default'] = 1;
            }

            if ($id > 0) {
                self::where('id', '=', $id)->where('member_id', '=', $member_id)->update($data);
            } else {
                $count = self::where('member_id', $member_id)->count();
                if ($count >= 10) {
                    throw new AddressException([
                        'msg' => '最多添加10个收获地址！',
                        'errorCode' => 12001
                    ]);
                }
                $data['member_id'] = $member_id;
                self::create($data);
            }
            Db::commit();
            return true;
        } catch (Exception $e) {
            Db::rollback();
            throw $e;
        }
    }

    /**
     * 删除收货地址
     * @param $id
     * @throws AddressException
     */
    public static function deleteAddress($id) {
        $member_id = Token::getCurrentUid();
        $address = self::get(['id' => $id, 'member_id' => $member_id]);
        if (!$address) {
            throw new AddressException();
        }
        if ($address['is_default'] == 1) {
            throw new AddressException([
                'msg' => '默认地址不能删除！',
                'errorCode' => 12002
            ]);
        }
        $address->delete();
    }

    /**
     * 设置默认地址
     * @param $id
     * @throws AddressException
     */
    public static function setDefaultAddress($id) {
        $member_id = Token::getCurrentUid();
        $address = self::get(['id' => $id, 'member_id' => $member_id]);
        if (!$address) {
            throw new AddressException();
        }

        Db::startTrans();
        try {

            self::update(['is_default' => 0], ['member_id' => $member_id]); // 把所有地址改为非默认
            $address->save(['is_default' => 1]);  //  把当前地址设为默认

            Db::commit();
        } catch (Exception $e) {
            Db::rollback();
        }

    }
}